package com.kaili.controller.web.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.common.util.ValidList;
import com.kaili.pojo.dto.delivery.EwbsDeliveryAddDTO;
import com.kaili.client.service.ILoginUserInfoService;
import com.kaili.common.PageRequest;
import com.kaili.common.util.FreemarkUtils;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.pojo.dto.delivery.EwbsDeliveryEditDTO;
import com.kaili.pojo.dto.delivery.EwbsDeliveryQueryDTO;
import com.kaili.pojo.entity.BaseCar;
import com.kaili.db.service.IBaseCarService;
import com.kaili.db.service.IHsBasicSeqService;
import com.kaili.db.service.IHsEwbsDeliveryService;
import com.kaili.db.service.IHsOptEwbAppointService;
import com.kaili.pojo.vo.*;
import com.kaili.common.exception.BaseExcept;
import com.kaili.except.ResponseStatus;
import com.kaili.feign.UserFeignClient;
import com.kaili.version.ApiVersion;
import freemarker.template.Configuration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.*;


@ApiVersion(1)
@RequestMapping("/{api_version}")
@RestController
@Api(tags = "派车接货服务", description = "派车接货服务相关API")
@Validated
public class DeliveryController {
    @Autowired
    IHsEwbsDeliveryService ewbsDeliveryService;
    @Autowired
    IHsBasicSeqService seqService;

    @Autowired
    ILoginUserInfoService loginUserInfoService;

    @Autowired
    IHsOptEwbAppointService ewbAppointService;

    @Autowired
    IBaseCarService carService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    Configuration configuration;

    @ApiOperation(value = "获取接货单号")
    @GetMapping("/deliverys/deliveryCode")
    String setDeliveryCode() {
        return seqService.seqByTypeWithType("JH");
    }

    @PostMapping(value = "/deliverys")
    @ApiOperation(value = "新增派车接货", notes = "新增派车接货")
    public ResponseStatus addDelivery(@Validated @RequestBody EwbsDeliveryAddDTO addDTO) {

        int ret = ewbsDeliveryService.addDelivery(addDTO);
        if (ret != 0) {
            return ResponseStatus.DELIVERY_ADD_ERR;
        }
        BaseCar baseCar = new BaseCar();
        baseCar.setId(addDTO.getCarId());
        baseCar.setCarStatus("在途");
        carService.updateById(baseCar);
        return ResponseStatus.RESPONSE_OK;
    }


    @GetMapping("/deliverys/unHandles")
    @ApiOperation(value = "查询未处理的预约登记列表")
    List<AppointQueryVO> queryUnHandleAppointList() throws BaseExcept {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("isHandle",0);
            map.put("siteId",loginUserInfoService.getLoginSiteId());
            return ewbAppointService.queryEwbAppointList(map);
    }


    @GetMapping("/deliverys")
    @ApiOperation(value = "分页查询派车接货列表")
    Page<DeliveryQueryVO> queryDeliveryPageList(@ModelAttribute EwbsDeliveryQueryDTO reqDTO) throws BaseExcept {
        if(reqDTO.getCur()!=null&&reqDTO.getPageSize()!=null){
            Page<DeliveryQueryVO> pager = new Page<DeliveryQueryVO>(reqDTO.getCur(), reqDTO.getPageSize());
            Map<Object,Object> map=new HashMap<>();
            map.putAll(new BeanMap(reqDTO));
            map.put("siteId",loginUserInfoService.getLoginSiteId());
            pager = ewbsDeliveryService.queryDeliveryPageList(pager,map);
            return pager;
        }
        throw new BaseExcept(ResponseStatus.DELIVERY_UNHANDLE_QUERY_ERR);
    }

    @GetMapping("/deliverys/{deliveryNo}/appoint")
    @ApiOperation(value = "根据接货单号查询预约信息")
    List<DeliveryAppointQueryVO> queryAppointListByDeliveryNo(@Pattern(regexp = "^[A-Za-z0-9]{0,30}$",message = "接货单号应为[A-Za-z0-9]组成的1-30位字符")
                                                              @PathVariable("deliveryNo")@ApiParam("接货单号") String deliveryNo) throws BaseExcept {
        Map searchMap = new HashMap();
        searchMap.put("deliveryNo", deliveryNo);
        searchMap.put("siteId",loginUserInfoService.getLoginSiteId());
        List<AppointQueryVO> oldlist = ewbsDeliveryService.queryAppointListByDeliveryNo(searchMap);
        List<DeliveryAppointQueryVO> newList = new ArrayList<>();
        for (AppointQueryVO appointQueryVO:oldlist) {
            DeliveryAppointQueryVO deliveryAppointQueryVO=new DeliveryAppointQueryVO();
            BeanUtils.copyProperties(appointQueryVO,deliveryAppointQueryVO);
            newList.add(deliveryAppointQueryVO);
        }
        return newList;
    }



    @PutMapping(value = "/deliverys")
    @ApiOperation(value = "修改并保存派车接货信息", notes = "修改并保存派车接货信息")
    public ResponseStatus doEditSaveDelivery(@Validated @RequestBody EwbsDeliveryEditDTO editDTO) {

        int ret = ewbsDeliveryService.updateDelivery(editDTO);
        if (ret != 0) {
            return ResponseStatus.DELIVERY_EDIT_SAVE_ERR;
        }
        return ResponseStatus.RESPONSE_OK;
    }


    @PostMapping(value = "deliverys/finish")
    @ApiOperation(value = "接货完成", notes = "接货完成")
    public ResponseStatus doFinishDelivery(@Size(min=1,message = "至少含有一个接货单号")
                                           @RequestBody @ApiParam("接货单号(数组格式)") ValidList<String> operationIds) {

        int ret = ewbsDeliveryService.doFinishDelivery(operationIds);
        if (ret != 0) {
            return ResponseStatus.DELIVERY_FINISH_ERR;
        }
        BaseCar baseCar;
        for(String operationId:operationIds){
            baseCar = new BaseCar();
            baseCar.setId(ewbsDeliveryService.selectById(operationId).getCarId());
            baseCar.setCarStatus("空闲");
            carService.updateById(baseCar);
        }
        return ResponseStatus.RESPONSE_OK;
    }

    @GetMapping("/deliverys/html")
    @ApiOperation(value = "获取接货单信息打印")
    public String queryDeliveryInPrint(@NotEmpty(message = "接货单号不得为空串") @RequestParam("deliveryNo") @ApiParam(value="接货单号逗号连接字符串") String deliveryNo) throws BaseExcept {
        if(StringUtils.isEmpty(deliveryNo)){
            throw new BaseExcept(ResponseStatus.PRINT_NULL);
        }
        String logo = userFeignClient.getCompanyLogo(Long.parseLong(LoginDetailUtils.getCompanyCode()));
        JSONObject json= JSON.parseObject(logo);
        List<String> deliveryNoList = Arrays.asList(deliveryNo.split(","));
        Map parm = new HashMap();
        parm.put("deliveryNoList",deliveryNoList);
        List<DeliveryQueryVO> list=ewbsDeliveryService.queryDeliveryList(parm);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list",list);
        map.put("companyName", LoginDetailUtils.getCompanyName());
        if(StringUtils.isEmpty(String.valueOf(json.get("data")))){
            map.put("pictureUrl","../api/static/logo.png");
        }else {
            map.put("pictureUrl", json.get("data"));
        }
        return FreemarkUtils.getPrintTemplate(configuration, "deliverNo", map);
    }

    @PostMapping("/queryDeliveryList")
    @ApiOperation(value = "查询派车接货列表")
    public List<DeliveryQueryVO> queryDeliveryList() throws BaseExcept {
        Map<String,Object> searchMap = new HashMap<>();
        searchMap.put("siteId",loginUserInfoService.getLoginSiteId());
        return ewbsDeliveryService.queryDeliveryList(searchMap);
    }

    @GetMapping("/deliverys/{deliveryNo}/deliveryDetail")
    @ApiOperation(value = "编辑时通过接货单号查询接货信息")
    public DeliveryInfoDetailQueryVO queryDeliveryInfoByNo(@Pattern(regexp = "^[A-Za-z0-9]{0,30}$",message = "接货单号应为[A-Za-z0-9]组成的1-30位字符")
                                                           @PathVariable("deliveryNo")@ApiParam("接货单号") String deliveryNo) throws BaseExcept {

        DeliveryInfoDetailQueryVO  deliveryInfoDetail = new DeliveryInfoDetailQueryVO();
        Integer loginSiteId = loginUserInfoService.getLoginSiteId();

        //查询派车单信息
        Map<String,Object> searchMap = new HashMap<>();
        searchMap.put("deliveryNo",deliveryNo);
        searchMap.put("siteId",loginSiteId);
        DeliveryQueryVO deliveryInfo = ewbsDeliveryService.queryDeliveryInfo(searchMap);
        deliveryInfoDetail.setDeliveryInfo(deliveryInfo);
        //查询派车单已关联预约信息列表
        List<AppointQueryVO> appointList = ewbsDeliveryService.queryAppointListByDeliveryNo(searchMap);
        deliveryInfoDetail.setAppointList(appointList);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("isHandle",0);
        map.put("siteId",loginSiteId);
        //查询未处理预约登记
        List<AppointQueryVO> unHandleAppointList = ewbAppointService.queryEwbAppointList(map);
        deliveryInfoDetail.setUnHandleAppointList(unHandleAppointList);
        return deliveryInfoDetail;
    }

    @PostMapping("/getDeliveryPointList")
    @ApiOperation(value = "获取接货点数据", notes = "获取接货点数据")
    List<DeliveryPointQueryVO> getDeliveryPointList(@RequestBody Map req) {
        return ewbsDeliveryService.getDeliveryPointList(req);
    }

    @ApiOperation(value = "删除接货单")
    @DeleteMapping("deliverys/{operationId}")
    ResponseStatus deleteDelivery(@Pattern(regexp = "^[0-9]{17,19}$",message = "接货单号流水号应为[0-9]组成的17-19位字符")
                                  @PathVariable("operationId") String operationId) {
        if (0 == ewbsDeliveryService.deleteDelivery(operationId)) {
            return ResponseStatus.RESPONSE_OK;
        } else {
            throw new BaseExcept(ResponseStatus.DELIVERY_DEL_ERR);
        }
    }

}
